package org.smartopen.unionpay.openapi.service.impl;

import lombok.RequiredArgsConstructor;
import org.smartopen.unionpay.openapi.constant.MqConstants;
import org.smartopen.unionpay.openapi.service.IMqService;
import org.smartopen.unionpay.openapi.service.dlx.DLXMessage;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

/**
 * @author ycc
 * @Date 2021-12-09
 */
@RequiredArgsConstructor
@Component
public class RabbitMqServiceImpl<T> implements IMqService<T> {

    private final RabbitTemplate rabbitTemplate;

    @Override
    public void sendMessage(String queueName, T message) {
        rabbitTemplate.convertAndSend(MqConstants.UNIONPAY_EXCHANGE, queueName, message);
    }

    /**
     * 延迟发送消息到队列
     * @param message 消息内容
     * @param times 延迟时间 单位毫秒
     */
    @Override
    public void sendMessage(String queueName, T message, long times) {
        DLXMessage dlxMessage = new DLXMessage(MqConstants.UNIONPAY_EXCHANGE,queueName, message,times);
        MessagePostProcessor processor = message1 -> {
            message1.getMessageProperties().setExpiration(times + "");
            return message1;
        };
        rabbitTemplate.convertAndSend(MqConstants.UNIONPAY_EXCHANGE,MqConstants.UNIONPAY_DEAD_LETTER_QUEUE_NAME, dlxMessage, processor);
    }
}
